package cn.codeforfun.export;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2017/2/18 0018.
 */
@RequestMapping("/export")
@Controller
public class ExportController {
    @Autowired
    private ExportService exportService;

    @RequestMapping("/list")
    @ResponseBody
    public Map list(String type) {
        Map map = exportService.list(type);
        return map;
    }

    @RequestMapping("/export")
    public void export(String type, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/binary;charset=ISO8859_1");
        String fileName = new String(String.valueOf(new Date().getTime()));
        //excel版本
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
        HSSFWorkbook workBook = exportService.export(type);
        ServletOutputStream outputStream = response.getOutputStream();
        try {
            workBook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
